#!/usr/bin/python3
import json
import sys

from PyQt5.QtCore import Qt, QModelIndex
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QTableWidget, \
    QTableWidgetItem, QGridLayout, QHBoxLayout, QCheckBox, QListView, QPushButton, QAbstractScrollArea, QHeaderView, \
    QAbstractItemView

version = '2.0'


class RestrictionsWindow(QWidget):

    def change_checkbox_state(self):
        row = self.params_table.currentRow()
        self.params_table.cellWidget(row, 3).chk_bx.nextCheckState()
        self.on_checkbox_change()

    def on_checkbox_change(self):
        if type(self.sender()) == QCheckBox:
            self.sender().parent().setFocus()
        current_restriction = self.params_table.item(self.params_table.currentRow(), 0).text()
        self.restrictions[self.current_restriction_category][current_restriction]['locked'] = \
            True if self.params_table.cellWidget(self.params_table.currentRow(), 3).chk_bx.checkState() != 0 else False
        print(self.restrictions)

    def change_table(self, index):
        self.current_restriction_category = self.categories_model.itemFromIndex(index).text()
        nrows = len(self.restrictions[self.current_restriction_category])
        self.params_table.setRowCount(nrows)
        self.params_table.setColumnCount(4)
        self.params_table.setHorizontalHeaderLabels(
            ["Элемент",
             "Функционал",
             "Значение",
             "Фиксирован"]
        )
        row = 0
        for key in self.restrictions[self.current_restriction_category]:
            self.params_table.setItem(row, 0, QTableWidgetItem(key))
            self.params_table.item(row, 0).setFlags(Qt.ItemIsEnabled)
            self.params_table.setItem(row, 1, QTableWidgetItem(
                self.restrictions[self.current_restriction_category][key]["translation"]
            ))
            self.params_table.item(row, 1).setFlags(Qt.ItemIsEnabled)
            self.params_table.setItem(row, 2, QTableWidgetItem(
                str(self.restrictions[self.current_restriction_category][key]["value"])
            ))
            # self.params_table.item(row, 2).setFlags(Qt.ItemFlag(63))
            cell_widget = QWidget()
            cell_widget.chk_bx = QCheckBox()
            lay_out = QHBoxLayout(cell_widget)
            lay_out.addWidget(cell_widget.chk_bx)
            lay_out.setAlignment(Qt.AlignCenter)
            lay_out.setContentsMargins(0, 0, 0, 0)
            cell_widget.setLayout(lay_out)
            cell_widget.mouseReleaseEvent = lambda event: self.change_checkbox_state()
            cell_widget.chk_bx.pressed.connect(lambda: self.on_checkbox_change())
            self.params_table.setCellWidget(row, 3, cell_widget)
            self.params_table.cellWidget(row, 3).chk_bx.setChecked(
                self.restrictions[self.current_restriction_category][key]["locked"]
            )

            row += 1
        self.params_table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
        self.params_table.resizeColumnsToContents()
        self.params_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)

    def save_restrictions(self):
        with open("restrictions2.json", 'w', encoding='utf-8') as out:
            json.dump(self.restrictions, out, ensure_ascii=False, indent=4)

    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QGridLayout()

        self.restrictions = json.load(open("restrictions.json"))
        self.categories_list_widget = QListView()
        self.categories_model = QStandardItemModel()
        self.categories_list_widget.setModel(self.categories_model)
        for key in self.restrictions.keys():
            self.categories_model.appendRow(QStandardItem(key))
        self.categories_list_widget.clicked[QModelIndex].connect(self.change_table)
        self.categories_list_widget.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked)
        self.layout.addWidget(self.categories_list_widget, 0, 0)

        self.categories_list_widget.setCurrentIndex(self.categories_model.index(0, 0))

        self.params_table = QTableWidget()
        self.params_table.setHorizontalHeaderLabels(
            ["Элемент",
             "Функционал",
             "Значение",
             "Фиксирован"]
        )
        self.layout.addWidget(self.params_table, 0, 1)
        # self.params_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.change_table(self.categories_model.index(0, 0))

        self.ok_button = QPushButton('Ok')
        self.ok_button.clicked.connect(self.save_restrictions)
        self.layout.addWidget(self.ok_button, 1, 0)
        self.cancel_button = QPushButton('Cancel')
        self.cancel_button.clicked.connect(lambda: self.parent().close())
        self.layout.addWidget(self.cancel_button, 1, 1)

        self.layout.setColumnMinimumWidth(1, 600)
        self.setLayout(self.layout)


# Creating the main window
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = f'KDE Restrictions ver. {version}'
        self.left = 300
        self.top = 200
        self.width = 900
        self.height = 400
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.restrictions_window_widget = RestrictionsWindow(self)
        self.setCentralWidget(self.restrictions_window_widget)

        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
